package com.jackykeke.HBuilder.integrate;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;

import com.jackykeke.service.WebAppService;
import com.jackykeke.utils.FileUtils;
import com.nostra13.dcloudimageloader.utils.L;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;

import io.dcloud.EntryProxy;
import io.dcloud.common.DHInterface.IApp;
import io.dcloud.common.DHInterface.ICore;
import io.dcloud.common.DHInterface.IOnCreateSplashView;
import io.dcloud.common.DHInterface.IWebview;
import io.dcloud.common.DHInterface.IWebviewStateListener;
import io.dcloud.common.util.ImageLoaderUtil;
import io.dcloud.feature.internal.sdk.SDK;

import static com.jackykeke.app.AppContants.SYS_DIR_CONF.OnlineWeb_save_dirPath;
import static com.jackykeke.app.AppContants.SYS_DIR_CONF.OnlineWeb_save_dirPath_1;


public class SDK_WebApp extends AppCompatActivity {


    public static final String UNZIP_WEBAPP = "UNZIP_WEBAPP";
    private BroadcastReceiver UnzipWebAppReceiver;
    private EntryProxy mEntryProxy;
    private ProgressDialog pDialog;
    private Context context;
    public String webUrl;
    private int mode;

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = SDK_WebApp.this;
//        requestWindowFeature(View.SYSTEM_UI_FLAG_FULLSCREEN);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //5.x开始需要把颜色设置透明，否则导航栏会呈现系统默认的浅灰色
            Window window = getWindow();
            View decorView = window.getDecorView();
            //两个 flag 要结合使用，表示让应用的主体内容占用系统状态栏的空间
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            decorView.setSystemUiVisibility(option);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
            //导航栏颜色也可以正常设置
//                window.setNavigationBarColor(Color.TRANSPARENT);
        } else {
            Window window = getWindow();
            WindowManager.LayoutParams attributes = window.getAttributes();
            int flagTranslucentStatus = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
            int flagTranslucentNavigation = WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
            attributes.flags |= flagTranslucentStatus;
            window.setAttributes(attributes);
        }

        webUrl = getIntent().getStringExtra("web");
        mode = getIntent().getIntExtra("mode", 0);
        if (mode == 1) {

            startWebAppService();


            UnzipWebAppReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    if (intent.getAction() == UNZIP_WEBAPP) {
                        int ok = intent.getIntExtra(WebAppService.UNZIP_WEBAPP_OK, -1);
                        switch (ok) {
                            case -1:
                                hideDialog();
                                break;
                            case 0:
                                injectWebView(savedInstanceState);
                                break;
                            case 1:
                                // 查询是否有manifest.json,有就复制一份到apps下面,没有就看apps那里有没有，
                                checkManifest();
                                injectWebView(savedInstanceState);
                                break;

                        }

                    }

                }
            };

            IntentFilter filter = new IntentFilter();
            filter.addAction(UNZIP_WEBAPP);
            registerReceiver(UnzipWebAppReceiver, filter);
            showDialog();
        } else if (mode == 2) {

            if (!webUrl.startsWith("http://") && !webUrl.startsWith("https://")) {
                webUrl = "http://" + webUrl;
            }
            setWebView(savedInstanceState);

        }

    }


    private void setWebView(Bundle savedInstanceState) {

        String webappPath = OnlineWeb_save_dirPath_1 + H5 + File.separator + "www";
        File file = new File(OnlineWeb_save_dirPath_1);
        if (!file.exists()) {
            file.mkdir();
        }
        File fileH5 = new File(OnlineWeb_save_dirPath_1 + H5);
        if (!fileH5.exists()) {
            fileH5.mkdir();
        }
        File fileWWW = new File(webappPath);
        if (!fileWWW.exists()) {
            fileWWW.mkdir();
        }

        if (new File(webappPath).exists()) {
            //复制assets的json文件到外部储存的文件夹
            FileUtils.assetCopyFile(getApplicationContext(), "manifest.json", new File(webappPath), "manifest.json");
            //修改外部储存json//

            String srcPath = webappPath + File.separator + "manifest.json";

            String secPath = webappPath + File.separator + "manifest1.json";

            changeManifestJSon(srcPath, secPath);

        } else {
            new File(webappPath).mkdir();
            FileUtils.assetCopyFile(getApplicationContext(), "manifest.json", new File(webappPath), "manifest.json");
            //修改外部储存json//

            String srcPath = webappPath + File.separator + "manifest.json";

            String secPath = webappPath + File.separator + "manifest1.json";

            changeManifestJSon(srcPath, secPath);
        }

        injectWebView(savedInstanceState);
    }

    private String H5 = "H5";


    private void injectWebView(Bundle savedInstanceState) {
        if (mEntryProxy == null) {
            FrameLayout rootView = new FrameLayout(SDK_WebApp.this);
            // 创建5+内核运行事件监听
            WebappModeListener wm = new WebappModeListener(SDK_WebApp.this, rootView, savedInstanceState);
            // 初始化5+内核
            mEntryProxy = EntryProxy.init(SDK_WebApp.this, wm);
            // 启动5+内核
            mEntryProxy.onCreate(SDK_WebApp.this, savedInstanceState, SDK.IntegratedMode.WEBAPP, null);
            setContentView(rootView);
        }
    }


    public void startWebAppService() {
        Thread startWebAppService = new Thread(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent();
                intent.putExtra("web", webUrl);
                WebAppService.runWebAppService(context, intent, WebAppService.WEBAPPSERVICE_CLASSNAME);
            }
        });
        startWebAppService.start();

    }


    private void checkManifest() {
        String webappPath = OnlineWeb_save_dirPath + new File(OnlineWeb_save_dirPath).list()[0] + File.separator + "www";
//        String destPath = AppContants.SYS_DIR_CONF.OnlineWeb_save_dirPath + "manifest.json";
        String appsPath =  /*"file:///android_asset/assets/apps/*/"manifest.json";
        // 查询是否有manifest.json,有就复制一份到apps下面,没有就看apps那里有没有，
        File ownManifest = new File(webappPath + File.separator + "manifest.json");
        if (!ownManifest.exists()) {
            FileUtils.assetCopyFile(getApplicationContext(), appsPath, new File(webappPath), "manifest.json");

            changeManifestJSon(webappPath + File.separator + "manifest.json", webappPath + File.separator + "manifest1.json");
        } else {
            L.d("webappPath----> appsPath");
        }
    }


    private void changeManifestJSon(String srcPath, String secPath) {


        if (new File(srcPath).exists()) {
            try {
                BufferedReader br = new BufferedReader(new FileReader(
                        new File(srcPath)));// 读取原始json文件
                BufferedWriter bw = new BufferedWriter(new FileWriter(
                        secPath));// 输出新的json文件
                String strBuffer = null, ws = "";
                while ((strBuffer = br.readLine()) != null) {
                    ws += strBuffer;
                }

                try {

                    JSONObject dataJson = new JSONObject(ws);
                    L.d("前dataJson-----" + dataJson.toString());
                    String id = dataJson.getString("id");
                    L.d("id-----" + id);
                    String name = dataJson.getString("name");
                    L.d("name-----" + name);
                    //修改 id name

                    String projectName = "";
                    if (mode == 1) {
                        projectName = new File(OnlineWeb_save_dirPath).list()[0];

                    } else if (mode == 2){
                        projectName ="H5";
                        dataJson.put("launch_path", webUrl);
                    }

                    dataJson.put("id", projectName);
                    dataJson.put("name", projectName);

                    ws = dataJson.toString();
                    L.d("后dataJson-----" + ws);
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                bw.write(ws);
                bw.flush();
                br.close();
                bw.close();
                FileUtils.rename(secPath, srcPath);
//                T.showShort(context, ws);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
//            T.showShort(context, "changeManifestJSon------没有manifest.json文件");
        }


    }


    private void showDialog() {

        if (pDialog == null) {
            pDialog = new ProgressDialog(SDK_WebApp.this, ProgressDialog.THEME_HOLO_LIGHT);
            pDialog.setMessage("努力加载中，请稍后");
            pDialog.setCancelable(false);
            pDialog.show();
            pDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    pDialog = null;
                }
            });
        }
    }

    private void hideDialog() {
        if (pDialog != null && pDialog.isShowing()) {
            pDialog.dismiss();
            pDialog = null;
        }
    }


    class WebappModeListener implements ICore.ICoreStatusListener, IOnCreateSplashView {

        private final Bundle savedInstanceState;
        //    LinearLayout btns = null;
        Activity activity = null;
        ViewGroup mRootView = null;
        ProgressDialog pd = null;
        IApp app = null;


        public WebappModeListener(Activity activity, ViewGroup rootView, Bundle savedInstanceState) {
            this.activity = activity;
            mRootView = rootView;
            this.savedInstanceState = savedInstanceState;
        }

        /**
         * 5+内核初始化完成时触发
         */
        @Override
        public void onCoreInitEnd(ICore coreHandler) {
            hideDialog();
            // 设置单页面集成的appid
            String appid = "TestAppid";//appid为null又是另一个界面了
            // 单页面集成时要加载页面的路径，可以是本地文件路径也可以是网络路径
//        String url = "file:///android_asset/apps/H5Plugin/www/index.html";
//        String url = "file:///android_asset/apps/eat/whatToEat.html";
//        String url = "file:///android_asset/apps/func/plus/camera.html";
            String url = null;
            if (mode == 1) {
                url = OnlineWeb_save_dirPath + new File(OnlineWeb_save_dirPath).list()[0]; /*+ File.separator*/
            } else if (mode == 2) {
                url = OnlineWeb_save_dirPath_1 + "H5";
            }
//            String url = "/apps/H5";

            // 设置启动参数,可在页面中通过plus.runtime.arguments;方法获取到传入的参数
            String args = "{url:'http://www.baidu.com'}";

            // 启动启动独立应用的5+ Webapp
            app = SDK.startWebApp(activity, url, args, new IWebviewStateListener() {
                // 设置Webview事件监听，可在监监听内获取WebIvew加载内容的进度
                @Override
                public Object onCallBack(int pType, Object pArgs) {
                    switch (pType) {
                        case IWebviewStateListener.ON_WEBVIEW_READY:
                            // WebApp准备加载事件
                            // 准备完毕之后添加webview到显示父View中，
                            // 设置排版不显示状态，避免显示webview时html内容排版错乱问题
                            View view = ((IWebview) pArgs).obtainApp().obtainWebAppRootView().obtainMainView();
                            view.setVisibility(View.VISIBLE);
//
                            if (view.getParent() != null) {
                                ((ViewGroup) view.getParent()).removeView(view);
                            }
                            mRootView.addView(view, 0);

                            break;
                        case IWebviewStateListener.ON_PAGE_STARTED:
                            // 首页面开始加载事件
                            pd = ProgressDialog.show(activity, "加载中", "0/100");
                            pd.setCancelable(true);
                            break;
                        case IWebviewStateListener.ON_PROGRESS_CHANGED:
                            // WebApp首页面加载进度变化事件
                            if (pd != null) {
                                pd.setMessage(pArgs + "/100");
                            }
                            break;
                        case IWebviewStateListener.ON_RECEIVED_ERROR:

//                            webUrl = "https://" + webUrl.substring(8);
//                            setWebView(savedInstanceState);
                            break;
                        case IWebviewStateListener.ON_PAGE_FINISHED:
                            // WebApp首页面加载完成事件
                            if (pd != null) {
                                pd.dismiss();
                                pd = null;
                            }
                            // 页面加载完毕，设置显示webview
//                            app.obtainWebAppRootView().obtainMainView().setVisibility(View.VISIBLE);
//                        mRootView.addView( app.obtainWebAppRootView().obtainMainView(), 0);
                            break;
                    }
                    return null;
                }
            }, this);


            // 在Widget集成时如果不需要显示splash页面可按照如下步骤操作
            // 1 删除onCreateSplash方法内的代码
            // 2 将5+mainView添加到rootview时将页面设置为不可见
            // 3 在onCloseSplash方法中将5+mainView设置为可见
            // 4 修改androidmanifest.xml文件 将SDK_WebApp的主题设置为透明
            // 注意！
            // 如果不显示splash页面会造成用户点击后页面短时间内会没有变化，
            // 可能会给用户造成程序没响应的错觉，
            // 所以开发者需要对5+内核启动到5+应用页面显示之间的这段事件进行处理


            app.setIAppStatusListener(new IApp.IAppStatusListener() {
                // 设置APP运行事件监听
                @Override
                public boolean onStop() {
                    // 应用运行停止时调用
                    mRootView.removeView(app.obtainWebAppRootView().obtainMainView());
                    // TODO Auto-generated method stub
                    return false;
                }

                @Override
                public void onStart() {
                    // 独立应用启动时触发事件
                }

                @Override
                public void onPause(IApp arg0, IApp arg1) {
                    // WebApp暂停运行时触发事件
                }

                @Override
                public String onStoped(boolean arg0, String arg1) {
                    // TODO Auto-generated method stub
                    return null;
                }
            });

        }

        // 5+SDK 开始初始化时触发
        @Override
        public void onCoreReady(ICore coreHandler) {
            try {
                // 初始化5+ SDK，
                // 5+SDK的其他接口需要在SDK初始化后才能調用
                SDK.initSDK(coreHandler);
                // 当前应用可使用全部5+API
                SDK.requestAllFeature();
                ImageLoaderUtil.initImageLoaderL(activity);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        /**
         * // 通过代码注册扩展插件的示例
         * private void regNewApi() {
         * // 扩展插件在js层的标识
         * String featureName = "T";
         * // 扩展插件的原生类名
         * String className = "com.HBuilder.integrate.webview.WebViewMode_FeatureImpl";
         * // 扩展插件的JS层封装的方法
         * String content = "(function(plus){function test(){return plus.bridge.execSync('T','test',[arguments]);}plus.T = {test:test};})(window.plus);";
         * // 向5+SDK注册扩展插件
         * SDK.registerJsApi(featureName, className, content);
         * }
         **/

        @Override
        public boolean onCoreStop() {
            // TODO Auto-generated method stub
            // 当返回false时候回关闭activity
            return false;
        }


        @Override
        public Object onCreateSplash(Context context) {
            return null;
        }

        @Override
        public void onCloseSplash() {
            // 如果不需要显示spalsh页面将此行代码移动至onCloseSplash事件内
            app.obtainWebAppRootView().obtainMainView().setVisibility(View.VISIBLE);
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mEntryProxy.destroy(this);
        mEntryProxy = null;
    }
}

